package org.shuma.goods.controller;


import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding;
import lombok.extern.slf4j.Slf4j;
import org.shuma.goods.common.BaseResponse;
import org.shuma.goods.common.ErrorCode;
import org.shuma.goods.common.ResultUtils;
import org.shuma.goods.domain.DTO.QueryOrder;
import org.shuma.goods.exception.BusinessException;
import org.shuma.goods.service.OrdersService;
import org.shuma.user.facade.UserFacade;
import org.shuma.user.vo.UserVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

import static org.shuma.goods.common.ErrorCode.PARAMS_ERROR;
import static org.shuma.goods.contant.UserConstant.ADMIN_STATUS;

@RestController
@Slf4j
public class OrderController {


    @Resource
    private OrdersService ordersService;


    @SofaReference(interfaceType = UserFacade.class,uniqueId = "${service.user.unique.id}",
            binding = @SofaReferenceBinding(bindingType = "bolt"))
    private UserFacade userFacade;

    public  final String  PRODUCT_TOP = "ProductTop";
    public  final String    EXCHANGE = "Exchange";
    public  final String    SALES_VOLUME = "SalesVolume";


    /**
     * 查询兑换量前20
     * @param queryOrder
     * @param userVo
     * @return
     */
    @GetMapping("/getProductTop")
    public BaseResponse<Map<String,Long>> ProductTop(@RequestBody QueryOrder queryOrder,
                                                     @RequestAttribute("userInfo")UserVo userVo) {


        //只有超管才可以查看
        if(userVo.getUserRole() != ADMIN_STATUS){
            throw new BusinessException(ErrorCode.NULL_AUTH,"只有超管可以查看");
        }

        // 入参为空,选择默认时间
        if(queryOrder.getBeforetime().isEmpty() && queryOrder.getAftertime().isEmpty()){
            return ResultUtils.success(defaultTime(PRODUCT_TOP));
        }

        //选择日期模版
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

        try {
            //校验 "yyyy-MM-dd HH:mm:ss" 时间类型是否合法
            LocalDateTime startLocalDateTime = LocalDateTime.parse(queryOrder.getBeforetime(), formatter);
            LocalDateTime endLocalDateTime = LocalDateTime.parse(queryOrder.getAftertime(), formatter);

            //转化为"yyyy-MM-dd"格式
            LocalDate  startLocalDate = startLocalDateTime.toLocalDate();
            LocalDate endLocalDate = endLocalDateTime.toLocalDate();

            checkTime(startLocalDate,endLocalDate);
            Map<String, Long> map = ordersService.getProductTop(startLocalDate, endLocalDate);

            return ResultUtils.success(map);
        } catch (DateTimeParseException e) {
            log.error("businessException: "+ e.getMessage(),e);
            return ResultUtils.error(PARAMS_ERROR,"日期格式不正确");
        }

    }


    /**
     * 查询兑换方式
     * @param queryOrder
     * @param userVo
     * @return
     */
    @GetMapping("/getExchange")
    public BaseResponse<Map<String,Long>> Exchange (@RequestBody QueryOrder queryOrder,
                                                    @RequestAttribute("userInfo")UserVo userVo){




        //只有超管才可以查看
        if(userVo.getUserRole() != ADMIN_STATUS){
            throw new BusinessException(ErrorCode.NULL_AUTH,"只有超管可以查看");
        }
        // 入参为空,选择默认时间
        if(queryOrder.getBeforetime().isEmpty() && queryOrder.getAftertime().isEmpty()){
            return ResultUtils.success(defaultTime(PRODUCT_TOP));
        }


        //选择日期模版
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

        try {
            //校验 "yyyy-MM-dd HH:mm:ss" 时间类型是否合法
            LocalDateTime startLocalDateTime = LocalDateTime.parse(queryOrder.getBeforetime(), formatter);
            LocalDateTime endLocalDateTime = LocalDateTime.parse(queryOrder.getAftertime(), formatter);

            //转化为"yyyy-MM-dd"格式
            LocalDate  startLocalDate = startLocalDateTime.toLocalDate();
            LocalDate endLocalDate = endLocalDateTime.toLocalDate();

            checkTime(startLocalDate,endLocalDate);
            Map<String, Long> map = ordersService.getExchange(startLocalDate, endLocalDate);

            return ResultUtils.success(map);
        } catch (DateTimeParseException e) {
            log.error("businessException: "+ e.getMessage(),e);
            return ResultUtils.error(PARAMS_ERROR,"日期格式不正确");
        }


    }

    /**
     * 查询兑换量
     * @param queryOrder
     * @param userVo
     * @return
     */
    @GetMapping("/getSalesVolume")

    public BaseResponse<Map<String,Long>> SalesVolume (@RequestBody QueryOrder queryOrder,
                                                       @RequestAttribute("userInfo")UserVo userVo){


        //只有超管才可以查看
        if(userVo.getUserRole() != ADMIN_STATUS){
            throw new BusinessException(ErrorCode.NULL_AUTH,"只有超管可以查看");
        }


        //选择日期模版
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

        try {
            //校验 "yyyy-MM-dd HH:mm:ss" 时间类型是否合法
            LocalDateTime startLocalDateTime = LocalDateTime.parse(queryOrder.getBeforetime(), formatter);
            LocalDateTime endLocalDateTime = LocalDateTime.parse(queryOrder.getAftertime(), formatter);

            //转化为"yyyy-MM-dd"格式
            LocalDate  startLocalDate = startLocalDateTime.toLocalDate();
            LocalDate endLocalDate = endLocalDateTime.toLocalDate();

            checkTime(startLocalDate,endLocalDate);

            Map<String, Long> map = ordersService.getSalesVolume(startLocalDate, endLocalDate);

            return ResultUtils.success(map);

        } catch (DateTimeParseException e) {
            log.error("businessException: "+ e.getMessage(),e);
            return ResultUtils.error(PARAMS_ERROR,"日期格式不正确");
        }



    }

    /**
     * 判断是否大于60天
     * @param startDate
     * @param endDate
     * @return
     */
    public  boolean isDateRangeGreaterThan60(LocalDate startDate, LocalDate endDate) {
        // 计算两个日期之间的天数
        long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);

        // 判断是否大于60天
        return daysBetween > 60;
    }

    /**
     * 校验日期是否符合规范
     * @param startTime
     * @param endTime
     */
    public void checkTime( LocalDate startTime,LocalDate endTime){
        // 获取今天的日期
        LocalDate today = LocalDate.now();

        //大于60天
        if(isDateRangeGreaterThan60(startTime,endTime)){
            throw new BusinessException(PARAMS_ERROR,"时间间隔大于60天");
        }
        //今天日期不可选
        if(startTime.isEqual(today) || endTime.isEqual(today)) {
            throw new BusinessException(PARAMS_ERROR,"今天日期不可选");
        }
        //未来日期不可选
        if(startTime.isAfter(today) || endTime.isAfter(today)){
            throw new BusinessException(PARAMS_ERROR,"未来日期不可选");
        }
        if(startTime.isAfter(endTime)){
            throw new BusinessException(PARAMS_ERROR,"起始时间不能大于终止时间");
        }
    }


    /**
     * 选择默认时间进行查询
     * @return
     */
    public  Map<String,Long> defaultTime(String type){

        // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 获取昨天的日期
        LocalDate yesterday = today.minusDays(1);
        // 获取过去第八天的日期
        LocalDate eightDaysAgo = today.minusDays(8);
        Map<String,Long> map = new HashMap<>();
        if(PRODUCT_TOP.equals(type)){
            map = ordersService.getProductTop(eightDaysAgo,yesterday);
        }
        if(EXCHANGE.equals(type)){
            map = ordersService.getExchange(eightDaysAgo,yesterday);
        }
        if(SALES_VOLUME.equals(type)){
            map = ordersService.getSalesVolume(eightDaysAgo,yesterday);
        }
        return map;

    }







}




